package ace.module.account.core.impl.service.callback.auth.handler.impl;

import ace.module.account.api.enums.IamAccountErrorEnum;
import ace.module.account.core.impl.service.callback.auth.handler.Oauth2AuthenticationCallbackHandler;
import ace.module.account.core.impl.service.callback.auth.handler.Oauth2AuthenticationCallbackHandlerManager;
import ace.module.account.core.impl.service.callback.auth.model.bo.Oauth2AuthenticationCallbackContext;
import ace.module.oauth2.server.api.model.dto.ext.Oauth2AceAuthResultDto;
import java.util.List;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * @author caspar
 * @date 2023/3/16 9:33
 */
@AllArgsConstructor
@Component
public class Oauth2AuthenticationCallbackHandlerManagerImpl
    implements Oauth2AuthenticationCallbackHandlerManager {

  private final List<Oauth2AuthenticationCallbackHandler> handlerList;

  @Override
  public Oauth2AceAuthResultDto authentication(Oauth2AuthenticationCallbackContext context) {
    for (Oauth2AuthenticationCallbackHandler handler : handlerList) {
      if (!handler.support(context)) {
        continue;
      }
      Oauth2AceAuthResultDto oauth2AceAuthResultDto = handler.authentication(context);
      if (oauth2AceAuthResultDto != null) {
        return oauth2AceAuthResultDto;
      }
    }
    Oauth2AceAuthResultDto resultDto = new Oauth2AceAuthResultDto();
    resultDto.setMessage(
        IamAccountErrorEnum.NOT_SUPPORT_AUTHENTICATION_TYPE.getDesc()
            + ","
            + context.getBodyModel().getOauth2AuthenticationCallbackInput().getAuthType());
    resultDto.setCode(IamAccountErrorEnum.NOT_SUPPORT_AUTHENTICATION_TYPE.getCode());
    return resultDto;
  }
}
